// views/system/ParamsManager.vue
<template>
  <div class="params-container">
    <el-card class="params-card">
      <template #header>
        <div class="card-header">
          <span class="title">系统参数配置</span>
          <el-button type="primary" @click="handleAdd">新增参数</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="参数名称">
            <el-input v-model="searchForm.key" placeholder="请输入参数名称" clearable />
          </el-form-item>
          <el-form-item label="参数分类" style="width: 220px">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option
                  v-for="item in categories"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
          v-loading="loading"
          :data="paramsList"
          border
          style="width: 100%"
      >
        <el-table-column prop="category" label="参数分类" width="150">
          <template #default="{ row }">
            <el-tag>{{ getCategoryLabel(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="configKey" label="参数名称" width="200" />
        <el-table-column prop="configValue" label="参数值" />
        <el-table-column prop="description" label="说明" width="200" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
                type="primary"
                link
                @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="page.current"
            v-model:page-size="page.size"
            :total="page.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑/新增对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增参数' : '编辑参数'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="参数分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
                v-for="item in categories"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="参数名称" prop="configKey">
          <el-input v-model="form.configKey" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="参数值" prop="configValue">
          <el-input v-model="form.configValue" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useConfigStore } from '@/stores/sysConfig.js'

const configStore = useConfigStore()

// 参数分类
const categories = [
  { label: '上传配置', value: 'UPLOAD' },
  { label: '系统配置', value: 'SYSTEM' },
  { label: '邮件配置', value: 'EMAIL' },
  { label: '安全配置', value: 'SECURITY' }
]

// 数据加载标志
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  key: '',
  category: ''
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 参数列表
const paramsList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  category: '',
  configKey: '',
  configValue: '',
  description: ''
})

// 表单校验规则
const rules = {
  category: [{ required: true, message: '请选择参数分类', trigger: 'change' }],
  configKey: [{ required: true, message: '请输入参数名称', trigger: 'blur' }],
  configValue: [{ required: true, message: '请输入参数值', trigger: 'blur' }]
}

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const data = await configStore.fetchConfigList({
      page: page.current,
      size: page.size,
      ...searchForm
    })
    paramsList.value = data.data.records
    console.log(paramsList.value)
    page.total = data.data.total
  } catch (error) {
    ElMessage.error('获取参数列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.current = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.key = ''
  searchForm.category = ''
  handleSearch()
}

// 分页相关
const handleSizeChange = (val) => {
  page.size = val
  fetchData()
}

const handleCurrentChange = (val) => {
  page.current = val
  fetchData()
}

// 获取分类标签
const getCategoryLabel = (value) => {
  const category = categories.find(item => item.value === value)
  return category ? category.label : value
}

// 新增参数
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(form, {
    category: '',
    configKey: '',
    configValue: '',
    description: ''
  })
  dialogVisible.value = true
}

// 编辑参数
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除参数
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确定要删除该参数吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await configStore.fetchDeleteConfig(row.configKey)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          const addData = {
            configKey: form.configKey,
            configValue: form.configValue,
            category: form.category,
            description: form.description
          }
          await configStore.fetchAddConfig(addData)
          ElMessage.success('新增成功')
        } else {
          const updateData = {
            configValue: form.configValue,
            category: form.category,
            description: form.description
          }

          await configStore.fetchUpdateConfig({
            configKey: form.configKey,
            ...updateData
          })
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败')
      }
    }
  })
}
</script>

<style scoped>
.params-container {
  padding: 20px;
}

.params-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>